<template>
  <!--地图起始位置-->
  <div id="map_box">
    <div class="map_mian">
      <div class="mapTs_top">
        {{ initialList.titleTs || "地图" }}:
        <i class="el-icon-close" @click="closeFn"></i>
      </div>

      <div class="left">
        <div class="provinces">
          <span class="title">选择搜索地区</span>
          <el-cascader
            v-model="provincesVle"
            :options="provincesData"
            :props="{ expandTrigger: 'hover' }"
            @change="provincesChange"
          ></el-cascader>
        </div>

        <div class="flex" style="justify-content: flex-start">
          <div class="mapSearch" style="width: 80%; float: left">
            <i class="el-icon-search"></i>
            <input
              type=""
              name=""
              @keyup.enter="mapSearchFn"
              v-model="mapSearchVle"
              placeholder="搜索信息"
              id=""
              value=""
            />
          </div>
          <el-button @click="mapSearchFn" type="primary" size="small"
            >搜索</el-button
          >
        </div>

        <div id="mapMain"></div>
      </div>

      <!--右边-->
      <div class="right">
        <div class="addressTitle flex">
          <span>经纬度：</span>
          <div class="input">
            <span style="width: 49%"
              ><el-input
                disabled
                v-model="mapList.location.lng"
                placeholder="经度"
              ></el-input
            ></span>
            <span style="width: 49%"
              ><el-input
                disabled
                v-model="mapList.location.lat"
                placeholder="纬度"
              ></el-input
            ></span>
          </div>
        </div>
        <div style="margin-top: 20px" class="addressTitle flex">
          <span>选择地址：</span>
          <div class="input">
            <el-input v-model="mapSlectVle" placeholder="请输入内容"></el-input>
          </div>
        </div>
        <div class="title" style="margin-top: 10px">
          注释：点击地图，显示附近位置
        </div>

        <!--点击附近地址数据-->
        <div
          id="mapSearch_tk"
          v-if="mapSearchList.length > 0 && mapType == 'clickList'"
        >
          <ul>
            <li
              v-for="(item, index) in mapSearchList"
              @click="mapSlectFn(index)"
            >
              <p style="background: #eee">{{ item.title }}</p>
              <p>{{ item.address }}</p>
            </li>
          </ul>
        </div>
        <div
          v-if="mapType == 'clickList'"
          class="page_box"
          style="margin: 10px 0px 0px 0px"
        >
          <el-pagination
            @current-change="addressChange"
            :current-page.sync="currentPage"
            :page-size="10"
            layout="total, prev, pager, next"
            :total="addressTotal"
          >
          </el-pagination>
        </div>

        <!--搜索附近地址数据-->
        <div
          id="mapSearch_tk"
          v-if="mapSearchList.length > 0 && mapType == 'searchList'"
        >
          <ul>
            <li
              v-for="(item, index) in mapSearchList"
              @click="mapSlectFn(index)"
            >
              <p style="background: #eee">{{ item.title }}</p>
              <p>{{ item.address }}</p>
            </li>
          </ul>
        </div>
        <div
          v-if="mapType == 'searchList'"
          class="page_box"
          style="margin: 10px 0px 0px 0px"
        >
          <el-pagination
            @current-change="searchAddressChange"
            :current-page.sync="searchCurrent"
            :page-size="10"
            layout="total, prev, pager, next"
            :total="addressTotal"
          >
          </el-pagination>
        </div>
      </div>

      <div class="mapBtn">
        <el-button type="info" @click="closeFn" size="small">取消</el-button>
        <el-button @click="submitFn" type="primary" size="small">保存</el-button
        >
      </div>
    </div>
  </div>
  <!--地图结束位置-->
</template>

<script type="text/javascript">
window.clickMarker = function clickMarker(res) {
  var address = res.attributes["address"].nodeValue,
    title = res.attributes["addressTitle"].nodeValue,
    latLng = res.attributes["latLng"].nodeValue;
  var endList = latLng.split(",");
  var obj = {
    address: address,
    title: address,
    lat: endList[0],
    lng: endList[1],
  };
  window.markerFn(obj);
};
import requestUrl from "@/util/requestUrl";
import utils from "@/util/utils";
import provinces from "@/util/provinces";
var map,
  _this = this,
  searchService,
  markers = [];
export default {
  name: "mapFm",
  props: {
    //status=-2 表示什么都没有传，1传值，做搜索
    initialList: {
      type: [Object],
      default: function () {
        return {
          status: -2,
        };
      },
    },
  },
  data() {
    return {
      mapSearchVle: "",

      mapSearchList: [],
      mapList: {
        location: {
          lat: "",
          lng: "",
        },
        status: -1,
      },

      currentPage: 1,
      addressTotal: 0,
      temporaryAddress: {}, //地理经纬度

      mapSlectVle: "", //选择地址
      provincesData: [], //省
      provincesVle: ["浙江省", "绍兴市", "柯桥区"],
      searchCounty: "柯桥区", //搜索地址

      //右边显示数据
      mapType: "clickList",
      searchCurrent: 1,
      searchData: [], //总的数据
    };
  },
  destory() {},
  mounted: function () {
    //省市区联动
    this.provincesData = provinces.data;

    //地图初始化
    this.initMap();

    var mapInfo = this.initialList;
    if (mapInfo.status == 1) {
      var center = new qq.maps.LatLng(
        mapInfo.location.lat,
        mapInfo.location.lng
      );
      this.mapSlectVle = mapInfo.address;
       this.mapList = this.initialList;
    }
    this.$nextTick((res) => {
      window.markerFn = this.getLatitude;
    });
  },
  methods: {
    //地址变化
    provincesChange: function (res) {
      var vel = this.provincesVle;
      this.searchCounty = vel[vel.length - 1];
    },

    //关闭
    closeFn: function (res) {
      this.$emit("closeMapFn", {
        show: 0,
      });
    },

    //获取经纬度
    getLatitude: function (obj) {
      var _this = this;
      //				this.mapSearchVle = obj.address;
      this.mapList = {
        address: obj.address,
        location: {
          lat: Number(obj.lat),
          lng: Number(obj.lng),
        },
        title: obj.title,
      };

      this.mapSlectVle = obj.address;

      var center = new qq.maps.LatLng(obj.lat, obj.lng);
      map = new qq.maps.Map(document.getElementById("mapMain"), {
        center: center,
        zoom: 13,
      });
      this.bindClick();
    },

    //地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap: function () {
      var _this = this;
      var center = new qq.maps.LatLng(29.95131, 120.60186);
      map = new qq.maps.Map(document.getElementById("mapMain"), {
        center: center,
        zoom: 13,
      });

      var latlngBounds = new qq.maps.LatLngBounds();
      //设置Poi检索服务，用于本地检索、周边检索
      searchService = new qq.maps.SearchService({
        //设置搜索范围为北京
        location: "北京",
        //设置搜索页码为1
        pageIndex: 0,
        //设置每页的结果数为5
        pageCapacity: 50,
        //设置动扩大检索区域。默认值true，会自动检索指定城市以外区域。
        autoExtend: true,
        //检索成功的回调函数
        complete: function (results) {
          //设置回调函数参数
          var pois = results.detail.pois;
          if (!pois) {
            _this.$message.error("未搜索到该地");
            return false;
          }

          for (var i = 0, l = pois.length; i < l; i++) {
            var poi = pois[i];
            //扩展边界范围，用来包含搜索到的Poi点
            latlngBounds.extend(poi.latLng);
          }

          //调整地图视野
          map.fitBounds(latlngBounds);

          //点击标点和事件
          _this.addMarker(results);
        },
        //若服务请求失败，则运行以下函数
        error: function () {
          _this.$message.error("出错了");
        },
      });

      //绑定单击事件添加参数
      qq.maps.event.addListener(map, "click", function (event) {
        var lat = event.latLng.getLat().toFixed(6);
        var lng = event.latLng.getLng().toFixed(6);
        var obj = "nearby(" + lat + "," + lng + ",1000)";
        _this.temporaryAddress = obj;
        _this.currentPage = 1;
        _this.returnMap(obj, 1);

        //点击地图填写经纬度
        var marker = new qq.maps.Marker({
          position: event.latLng,
          map: map,
          icon: new qq.maps.MarkerImage("../../static/image/GPS.png"),
        });
        qq.maps.event.addListener(map, "click", function (event) {
          marker.setMap(null);
        });
        _this.mapList.location.lng = lng;
        _this.mapList.location.lat = lat;
        _this.mapSlectVle = "";
      });
    },

    //添加标点
    addMarker: function (results) {
      var _this = this;
      var data = results.detail.pois;
      var infoWin = new qq.maps.InfoWindow({
        map: map,
      });

      //地址数据
      let addressList = [];

      for (var i = 0; i < data.length; i++) {
        (function (n) {
          var marker = _this.marker;
          marker = new qq.maps.Marker({
            position: data[n].latLng,
            map: map,
          });

          //记录标记，好清除
          marker.setTitle(i + 1);
          markers.push(marker);

          qq.maps.event.addListener(marker, "click", function () {
            infoWin.open();
            infoWin.setContent(
              '<div style="width:200px;text-align:center;white-space:' +
                'nowrap;margin:10px;"> ' +
                "<div>" +
                data[n].name +
                "</div>" +
                '<div style="margin-top: 10px;">  <button style="width: 80px;border: 0;height: 30px;line-height: 30px;border-radius: 5px;text-align: center;background: #05AEFD;color:#fff;"  onclick="clickMarker(this)" address="' +
                data[n].address +
                '"' +
                'addressTitle="' +
                data[n].name +
                '"' +
                'latLng="' +
                data[n].latLng +
                '">导入经纬度</button></div>' +
                "</div>"
            );
            infoWin.setPosition(data[n].latLng);
          });
        })(i);

        //显示地图
        addressList.push({
          location: {
            lat: data[i].latLng.lat,
            lng: data[i].latLng.lng,
          },
          address: data[i].address,
          title: data[i].name,
          id: data[i].id,
          phone: data[i].phone,
          postcode: data[i].postcode,
        });
      }

      this.mapType = "searchList";
      this.mapSearchList = addressList.slice(0, 10);
      this.searchData = addressList;
      this.addressTotal = addressList.length;
    },

    //导入经纬度
    clickMarker: function (res) {
      console.log(res,'sdsdsd')
    },

    //搜索分页
    searchAddressChange: function (res) {
      let data = this.searchData,
        end = res * 10,
        start = end - 10;
      this.searchCurrent = res;
      this.mapSearchList = data.slice(start, end);
    },

    //分页
    addressChange: function (res) {
      this.returnMap(this.temporaryAddress, res);
    },

    //根据经纬度返回地址
    returnMap: function (obj, page) {
      var vle = this.mapSearchVle;
      this.$jsonp("https://apis.map.qq.com/ws/place/v1/search", {
        boundary: obj,
        key: "CPUBZ-J5NK6-WY7SH-MOH44-ZS4S5-U3BCG",
        output: "jsonp",
        page_size: 10,
        page_index: page,
      }).then((res) => {
        // 返回的jsonp数据不会放这里，而是在 window.jsonpCallback
        if (res.data.length > 0) {
          this.mapSearchList = res.data;
          this.addressTotal = res.count;
        } else {
          this.mapSearchList = [];
        }
      });
    },

    //清除地图上的marker
    clearOverlays: function (overlays) {
      var overlay;
      while ((overlay = overlays.pop())) {
        overlay.setMap(null);
      }
    },

    //地图搜索
    mapSearchFn: function (res) {
      var keyword = this.mapSearchVle;
      var searchCounty = this.searchCounty;
      if (!searchCounty) {
        this.$message.error("请选择要搜索的区域");
        return false;
      }

      if (!keyword) {
        this.$message.error("请输入要搜索的相关信息");
        return false;
      }

      this.clearOverlays(markers);
      //根据输入的城市设置搜索范围
      searchService.setLocation(searchCounty);
      //根据输入的关键字在搜索范围内检索
      searchService.search(keyword);
    },

    //选中
    mapSlectFn: function (index) {
      var _this = this;
      var list = this.mapSearchList[index];
      var center = new qq.maps.LatLng(list.location.lat, list.location.lng);
      this.mapList = list;

      list.status = 1;
      this.mapSearchList = [];

      this.mapSlectVle = list.address;
      this.mapSearchVle = "";

      this.currentPage = 1;
      this.addressTotal = 0;
    },

    //绑定事件
    bindClick: function (res) {
      var _this = this;
      qq.maps.event.addListener(map, "click", function (event) {
        var lat = event.latLng.getLat().toFixed(6);
        var lng = event.latLng.getLng().toFixed(6);
        var obj = "nearby(" + lat + "," + lng + ",1000)";
        _this.temporaryAddress = obj;
        _this.currentPage = 1;
        _this.returnMap(obj, 1);

        //点击地图填写经纬度
        var marker = new qq.maps.Marker({
          position: event.latLng,
          map: map,
          icon: new qq.maps.MarkerImage("../../static/image/GPS.png"),
        });
        qq.maps.event.addListener(map, "click", function (event) {
          marker.setMap(null);
        });
        _this.mapList.location.lng = lng;
        _this.mapList.location.lat = lat;
        _this.mapSlectVle = "";
      });
    },

    //保存
    submitFn: function (res) {
      var list = this.mapList;

      if (!this.mapSlectVle) {
        this.$message.error("请输入对应地址");
        return false;
      } else {
        list.address = this.mapSlectVle;
      }

      this.$emit("submitFn", list);
    },
  },
  watch: {
    initText() {},
  },
};
</script>

<style lang="less">
/*地图起始位置*/

#map_box {
  width: 100%;
  height: 100vh;
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  background: rgba(000, 000, 000, 0.5);
  .map_mian {
    width: 1350px;
    height: 830px;
    margin: auto;
    background: #fff;
    transform: translate(-50%, -50%);
    position: fixed;
    left: 50%;
    top: 50%;
    border-radius: 6px;
    overflow: hidden;
    .mapTs_top {
      width: 96%;
      height: 40px;
      background: #eee;
      line-height: 40px;
      padding: 0px 2%;
      i {
        float: right;
        margin-top: 10px;
        font-size: 20px;
        cursor: pointer;
      }
    }
    /*左边*/
    .left {
      width: 870px;
      float: left;
    }
    .right {
      width: 470px;
      margin-left: 10px;
      float: left;
      .addressTitle {
        width: 100%;
        height: 35px;
        margin-top: 20px;
        span {
          width: 80px;
          display: inline-block;
        }
        .input {
          width: 350px;
          margin-left: 10px;
        }
      }
      .title {
        width: 100%;
        height: 35px;
        line-height: 35px;
        margin-top: 20px;
        font-weight: bold;
      }
    }
  }
  .provinces {
    width: 95%;
    overflow: hidden;
    padding: 5px 2.5%;
    margin-top: 10px;
    .title {
      margin-right: 20px;
    }
  }
  #mapMain {
    width: 96%;
    height: 600px;
    margin: 15px auto auto auto;
    position: relative;
  }
  .mapSearch {
    width: 96%;
    height: 35px;
    border-radius: 35px;
    border: 1px solid #d9d9d9;
    padding: 2px 1%;
    margin: 10px 10px 10px 20px;
    i {
      color: #888;
      font-size: 18px;
      line-height: 35px;
      margin-left: 8px;
    }
    input {
      width: 90%;
      height: 35px;
      border: 0px;
      padding: 0px 2%;
    }
  }
  #mapSearch_tk {
    width: 100%;
    margin: auto;
    z-index: 10000000;
    left: 2%;
    top: 110px;
    min-height: 500px;
    background: #fff;
    font-size: 13px;
    padding: 5px 3%;
  }
  #mapSearch_tk li {
    width: 95%;
    padding: 5px 0px;
    line-height: 20px;
    border-bottom: 1px solid #efeeee;
  }
  .mapBtn {
    width: 96%;
    overflow: hidden;
    text-align: right;
    margin: 30px auto auto auto;
  }
}
/*地图结束位置*/
</style>